﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Recharge
{
    /// <summary>
    /// 客户充值单收银
    /// </summary>
    public partial class CheckedOutRechargeBillView : UserControl, IView
    {
        #region Property
        /// <summary>
        /// 充值单号
        /// </summary>
        private Guid Id = Guid.Empty;
        Promise _promise = new Promise();
        /// <summary>
        /// 支付渠道
        /// </summary>
        List<WebRef.EPayRecord> listPayRecord = new List<WebRef.EPayRecord>();
        #endregion

        #region Method
        /// <summary>
        /// 构造方法
        /// </summary>
        public CheckedOutRechargeBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtTicketNumber, "票据号码", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.ctlEditCheckOutMemo, "收银备注", true));
        }
        public CheckedOutRechargeBillView(Guid Id)
            : this()
        {
            this.Id = Id;
        }
        /// <summary>
        /// 绑定收银渠道
        /// </summary>
        private void BindPayWay()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.EMasterDataItem> result = new LocalService.QueryService().QueryMasterDataItemList(Domain.Constant.MasterDataCodes.PayChannel, null, null);
                this.BeginInvoke(new Action<ListResult<WebRef.EMasterDataItem>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        ctlLookUpPayChannel.Properties.DataSource = p.Data.Items;
                        ctlLookUpPayChannel.Properties.DisplayMember = "Name";
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Reject();
                    }
                }), result);
            });
        }
        /// <summary>
        /// 绑定票据类型
        /// </summary>
        private void BindTicketType()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.EMasterDataItem> result = new LocalService.QueryService().QueryMasterDataItemList(Domain.Constant.MasterDataCodes.InvoiceTypes, null, null);
                this.BeginInvoke(new Action<ListResult<WebRef.EMasterDataItem>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        this.ctlSearchLookUpTicketType.Properties.DataSource = p.Data.Items;
                        this.ctlSearchLookUpTicketType.Properties.DisplayMember = "Name";
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Resolve();
                    }
                }), result);
            });
        }
        /// <summary>
        /// 充值单信息初始
        /// </summary>
        private void InitInfo()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.VRechargeBill> result = new Service.GetService().GetRechargeBill(Id);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        this.ctlLabelNumber.Text = result.Data.Number;
                        this.txtCustomer.Text = result.Data.CustomerName;
                        this.txtRechargeItem.Text = result.Data.RechargeItemName;
                        this.txtYSAmount.EditValue = result.Data.BoughtPrice;
                        this.txtCRAmount.Text = result.Data.RechargeItemAmount.ToString();
                        this.txtSalesMan.Text = result.Data.SalesManagerName;
                        this.txtSalesCom.EditValue = result.Data.SalesCommissionAmount;
                        this.txtRechargeRemark.Text = result.Data.Memo;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 获取已添加的所有的支付方式
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EPayRecord> GetListPayRecord()
        {
            List<WebRef.EPayRecord> list = this.GVData.DataSource as List<WebRef.EPayRecord>;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].PayAmount <= 0)
                {
                    UIContext.Current.ViewManager.ShowWarning("支付金额应大于0！");
                    return null;
                }
            }
            return list;
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        private bool ValidataData()
        {
            if (this.listPayRecord.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择收银渠道！");
                return false;
            }
            if (GetListPayRecord() == null)
            {
                return false;
            }
            string message = null;
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 收银
        /// </summary>
        private void CheckOutRechargeBill()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CheckOutService().CheckOutRechargeBill(Id, GetCheckOutData(), GetListPayRecord().ToArray());
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }

        private bool ValidateCheckOutData()
        {
            WebRef.EMasterDataItem selectedItem = ctlSearchLookUpTicketType.GetSelectedValue<WebRef.EMasterDataItem>();
            if (selectedItem != null)
            {
                string invoiceNumber = txtTicketNumber.Text.Trim();
                if (string.IsNullOrEmpty(invoiceNumber))
                {
                    return false;
                }
            }
            return true;
        }

        private WebRef.CheckOutData GetCheckOutData()
        {
            WebRef.EMasterDataItem selectedItem = ctlSearchLookUpTicketType.GetSelectedValue<WebRef.EMasterDataItem>();
            if (selectedItem == null)
            {
                return null;
            }
            else
            {
                return new WebRef.CheckOutData()
                {
                    InvoiceType = selectedItem.Code,
                    InvoiceNumber = txtTicketNumber.Text.Trim(),
                    Memo = ctlEditCheckOutMemo.Text.Trim()
                };
            }
        }
        #endregion

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("checked", Resources.isSettling, "收银", btnChecked_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", btnCancel_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(BindPayWay)
                .Then(BindTicketType)
                .Then(InitInfo)
                .Run(null);
        }
        public void Resume(ViewResumeArgs args)
        {

        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("客户充值单收银");
        }
        #endregion

        #region actions
        /// <summary>
        /// 添加支付方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddPayWay_Click(object sender, EventArgs e)
        {
            WebRef.EMasterDataItem emdItem = ctlLookUpPayChannel.EditValue as WebRef.EMasterDataItem;
            if (emdItem != null)
            {
                WebRef.EPayRecord item = new WebRef.EPayRecord(emdItem.Code, emdItem.Name, 0, "");
                item.BillId = Id;
                listPayRecord.Add(item);
                this.GCCashInfo.DataSource = null;
                this.GCCashInfo.DataSource = listPayRecord;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnChecked_Click(object sender, object e)
        {
            if (ValidataData() && ValidateCheckOutData())
            {
                CheckOutRechargeBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RIButtonRemove_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "移除")
            {
                WebRef.EPayRecord item = this.GVData.GetRow(GVData.FocusedRowHandle) as WebRef.EPayRecord;
                listPayRecord.Remove(item);
                if (listPayRecord.Count == 0)
                {
                    this.GCCashInfo.DataSource = null;
                }
                else
                {
                    this.GCCashInfo.DataSource = null;
                    this.GCCashInfo.DataSource = listPayRecord;
                }
            }
        }
        #endregion
    }
}
